import { login } from "@/api/user";
import sessionStorage from "@/sessionStorage/sessionStorage";
import router from "@/router";
import { getInfo } from "@/api/user";
import store from "..";
const user = {
  state: {
    userName: "",
    token: "",
    roles: [],
    permissions: [],
  },
  getters: {
    userIsLogin(state) {
      return state.userName !== "" && state.token !== "";
    },
    permissions(state) {
      return state.permissions;
    },
    getToken(state) {
      return state.token;
    },
  },
  mutations: {
    SAVE_USER(state, userName) {
      state.userName = userName;
    },
    SAVE_TOKEN(state, token) {
      state.token = token;
    },
    RESET_STATE: (state) => {
      Object.assign(state, getDefaultState());
    },
    SAVE_ROLES(state, roles) {
      state.roles = roles;
    },
    SAVE_PERMISSIONS(state, permissions) {
      state.permissions = permissions;
    },
  },
  actions: {
    /**
     * 此处用来处理登陆的逻辑，如果登陆成功会在vuex中保存用户的信息
     * vuex中的用户信息用来报纸用户是否已经登录
     * @param {*} param0
     * @param {*} user
     */
     LOGIN_actions({ commit }, user) {
      return new Promise(function (resolve) {
        login(user).then((res) => {
          if (res.status === 200) {
            // vuex的使用是为了保障数据的响应式
            commit("SAVE_USER", res.data.ydlUser.userName);
            sessionStorage.saveSessionString(
              "userName",
              res.data.ydlUser.userName
            );
            commit("SAVE_TOKEN", res.data.token);
            sessionStorage.saveSessionString("token", res.data.token);
            // console.log("login=>"+store.getters.getToken)
          resolve(res)
          }
        }
        )
      })
  },



    /*LOGIN_actions({ commit }, user) {
      login(user).then((res) => {
        if (res.status === 200) {
          // vuex的使用是为了保障数据的响应式
          commit("SAVE_USER", res.data.ydlUser.userName);
          sessionStorage.saveSessionString(
            "userName",
            res.data.ydlUser.userName
          );
          commit("SAVE_TOKEN", res.data.token);
          sessionStorage.saveSessionString("token", res.data.token);
          // console.log("login=>"+store.getters.getToken)
        
          return new Promise(
            (reslove) => reslove(),
            () => {}
          );
        }
      });
    },*/
    GET_INFO({ commit }) {
      return new Promise((resolve) => {
        getInfo().then((res) => {
          // console.log(res)
          commit("SAVE_ROLES", res.data.role_tag);
          sessionStorage.saveSessionString("roles", res.data.role_tag);
          commit("SAVE_PERMISSIONS", res.data.perms);
          sessionStorage.saveSessionString("permissions", res.data.perms);
          resolve();
        });
      });
    },
    LOGINOUT({ commit }) {
      return new Promise((resolve) => {
        // console.log(res)
        commit("RESET_STATE");
        resolve();
      });
    },
  },
};

export default user;
